'use client'

import { Dialog, DialogHeader, DialogTitle, DialogContent, DialogFooter } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { useEffect, useState } from 'react'
import { useSearchParams, useRouter } from 'next/navigation'
import useRequest from '@/utils/request'
import { useDispatch } from 'react-redux'
import { setConfig } from '@/store/config-slice'

function CircleCheckIcon(props) {
  return (
    <svg
      {...props}
      xmlns="http://www.w3.org/2000/svg"
      width="24"
      height="24"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <circle cx="12" cy="12" r="10" />
      <path d="m9 12 2 2 4-4" />
    </svg>
  )
}
export default function PayDialog() {
  const [open, setOpen] = useState(false)
  const searchParams = useSearchParams()
  const router = useRouter()
  const request = useRequest()
  const dispatch = useDispatch()

  useEffect(() => {
    const payStatus = searchParams.get('pay_status')
    if (payStatus === 'success') {
      setOpen(true)

      request.get('account/userinfo').then(res => {
        dispatch(setConfig(res.data))
        // 清除 pay_status
        router.push('/projects')
      })
    }
  }, [])

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>Congrats</DialogTitle>
        </DialogHeader>
        <div className="flex flex-col items-center justify-center gap-4 py-8">
          <div className="relative w-16 h-16 bg-green-500 rounded-full flex items-center justify-center">
            <CircleCheckIcon className="size-12 text-white" />
            <div className="absolute inset-0 animate-confetti">
              <div className="w-full h-full bg-confetti bg-[length:40px_40px] animate-confetti-loop" />
            </div>
          </div>
          <p className="text-lg font-medium">Pay Success!</p>
        </div>
        <DialogFooter>
          <div>
            <Button type="button" onClick={() => setOpen(false)}>
              Ok
            </Button>
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
